<template>
	<el-dialog
		v-model="visible"
		title="选择标签"
		:width="store.tagSimple ? 400 : 700"
		:destroy-on-close="true"
		:before-close="handleBeforeClose"
	>
		<select-tag-panel
			ref="selectTagPanelRef"
			:simple="store.tagSimple"
			:showTab="store.tagShowTab"
			:type="typeFormatter"
		/>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleDialogCancel">取消</el-button>
				<el-button type="primary" @click="handleDialogSubmit">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
	import { globalStore } from '@/store'
	import customerApi from '@/api/biz/customerApi'
	import { ElMessage } from 'element-plus'

	const store = globalStore()

	const emits = defineEmits(['finish'])

	const selectTagPanelRef = ref(null)

	const customerCode = ref(null)
	const type = ref(null) // 2-客户私海 3-客户公海 4-线索私海 5-线索公海
	const typeFormatter = computed(() => {
		if ([2, 3].includes(type.value)) {
			return 2
		} else if ([4, 5].includes(type.value)) {
			return 1
		}
		return 0
	})

	/**
	 * 弹窗
	 */
	const visible = ref(false)
	const handleDialogCancel = () => {
		selectTagPanelRef.value?.clear()
		visible.value = false
	}
	const handleDialogSubmit = () => {
		if (!selectTagPanelRef.value?.tagIdList.length) {
			return ElMessage({
				message: '请至少选择一个标签',
				type: 'warning'
			})
		}

		customerApi
			.addTag({
				customerCode: customerCode.value,
				type: type.value,
				ids: selectTagPanelRef.value?.tagIdList
			})
			.then((res) => {
				store.tagFinishStatus = true
				if (store.dashboardNode?.phoneData.code === customerCode.value) {
					store.tagIdList = selectTagPanelRef.value?.tagIdList
					store.tagNameList = selectTagPanelRef.value?.tagNameList
				}
				emits('finish', selectTagPanelRef.value?.tagIdList)
				handleDialogCancel()
			})
	}
	const handleBeforeClose = () => {
		handleDialogCancel()
	}

	const open = (code, tagType, idList) => {
		store.tagFinishStatus = false
		customerCode.value = code
		type.value = tagType
		visible.value = true
		nextTick(() => {
			selectTagPanelRef.value?.setTagIdList(idList)
		})
	}

	defineExpose({
		open
	})
</script>

<style scoped lang="less"></style>
